BinaryCrossEntropyGrad
计算二元交叉熵损失函数的梯度。
\[dx_n = dL'_n \cdot w_n \cdot \frac{x_n - y_n}{x_n(1 - x_n) + \epsilon}\]
其中 \(x_n\) 是前向预测值, \(y_n\) 是目标值, \(w_n\) 是样本权重, \(dL'_n\) 是上游梯度。reduction 参数决定了 \(dL'_n\) 的广播方式。
- 输入:
input_x - 前向传播时的预测值张量。
input_y - 前向传播时的目标值(标签)张量。
weight - (可选) 前向传播时使用的权重张量。
dloss - 来自后一层的上游梯度。
dx - (输出) 梯度结果的存储地址。
param - 参数数组,3个long long类型数据,按顺序包含以下元素:
input_size - 目标值张量的大小。
reduction - 前向传播时使用的规约类型 (0: None, 1: Mean, 2: Sum)。
weight_defined - 权重是否有效的标志。若为非0,则`weight`参数必须提供。
core_mask - 核掩码。
- 输出:
dx - 写入计算出的对 input_x 的梯度。
- 支持平台:
FT78NEMT7004
备注
FT78NE 支持fp32
MT7004 支持fp16, fp32
共享存储版本:
-
void fp_binary_cross_entropy_grad_s(float *input_x, float *input_y, float *weight, float *dloss, float *dx, long long *param, int core_mask)
-
void hp_binary_cross_entropy_grad_s(half *input_x, half *input_y, half *weight, half *dloss, half *dx, long long *param, int core_mask)
C调用示例:
1//FT78NE示例
2#include <stdio.h>
3#include <binary_cross_entropy_grad.h>
4int main(int argc, char* argv[]) {
5 float *input_x = (float *)0xA0000000; // forward input_x, DDR
6 float *input_y = (float *)0xB0000000; // forward input_y
7 float *weight = (float *)0xC0000000; // forward weight
8 float *dloss = (float *)0xD0000000; // upstream gradient
9 float *dx = (float *)0xE0000000; // output gradient dx
10
11 int input_size = 1024;
12 int reduction = 1; // Mean
13 int weight_defined = 1; // true
14 long long param[3] = {input_size, reduction, weight_defined};
15 int core_mask = 0xff;
16
17 fp_binary_cross_entropy_grad_s(input_x, input_y, weight, dloss, dx, param, core_mask);
18 return 0;
19}
私有存储版本:
-
void fp_binary_cross_entropy_grad_p(float *input_x, float *input_y, float *weight, float *dloss, float *dx, long long *param)
-
void hp_binary_cross_entropy_grad_p(half *input_x, half *input_y, half *weight, half *dloss, half *dx, long long *param);
C调用示例:
1//FT78NE示例
2#include <stdio.h>
3#include <binary_cross_entropy_grad.h>
4int main(int argc, char* argv[]) {
5 float *input_x = (float *)0x10810000; // forward input_x, L2
6 float *input_y = (float *)0x10820000; // forward input_y
7 float *weight = (float *)0x10830000; // forward weight
8 float *dloss = (float *)0x10840000; // upstream gradient
9 float *dx = (float *)0x10850000; // output gradient dx
10
11 int input_size = 1024;
12 int reduction = 1; // Mean
13 int weight_defined = 0; // false
14 long long param[3] = {input_size, reduction, weight_defined};
15
16 fp_binary_cross_entropy_grad_p(input_x, input_y, weight, dloss, dx, param);
17 return 0;
18}